package com.mdd.admin.service.system.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.service.order.IOrderRefundService;
import com.mdd.admin.service.order.IOrderService;
import com.mdd.admin.service.system.ICouponReceiveService;
import com.mdd.admin.service.system.ICouponService;
import com.mdd.admin.service.system.ISystemDevCrontabService;
import com.mdd.admin.task.*;
import com.mdd.admin.validate.common.PageParam;
import com.mdd.admin.validate.system.SystemDevCrontabParam;
import com.mdd.admin.vo.system.SystemDevCrontabListVo;
import com.mdd.admin.vo.system.SystemDevCrontabDetailVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.system.SystemDevCrontab;
import com.mdd.common.enums.SystemDevCrontabEnum;
import com.mdd.common.mapper.system.SystemDevCrontabMapper;
import com.mdd.common.utils.ArrayUtil;
import com.mdd.common.utils.TimeUtil;
import com.mdd.common.utils.UrlUtil;
import com.mdd.common.config.GlobalConfig;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.*;

/**
 * 定时任务实现类
 * @author panweiliang
 */
@Service
public class SystemDevCrontabServiceImpl implements ISystemDevCrontabService {
        
    @Resource
    SystemDevCrontabMapper systemDevCrontabMapper;

    @Resource
    private CronTaskRegistrar cronTaskRegistrar;

    @Resource
    private IOrderService iOrderService;

    @Resource
    private IOrderRefundService iOrderRefundService;

    @Resource
    private ICouponReceiveService iCouponReceiveService;

    @Resource
    private ICouponService couponService;

    /**
     * 定时任务列表
     *
     * @author panweiliang
     * @return PageResult<SystemDevCrontabListVo>
     */
    @Override
    public PageResult<SystemDevCrontabListVo> list(PageParam pageParam) {
        Integer page  = pageParam.getPageNo();
        Integer limit = pageParam.getPageSize();
        QueryWrapper<SystemDevCrontab> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("update_time");
        IPage<SystemDevCrontab> iPage = systemDevCrontabMapper.selectPage(new Page<>(page, limit), queryWrapper);
        List<SystemDevCrontabListVo> list = new LinkedList<>();
        for(SystemDevCrontab item : iPage.getRecords()) {
            SystemDevCrontabListVo vo = new SystemDevCrontabListVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtil.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtil.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 定时任务详情
     *
     * @author panweiliang
     * @param id 主键参数
     * @return SystemDevCrontab
     */
    @Override
    public SystemDevCrontabDetailVo detail(Integer id) {
        SystemDevCrontab model = systemDevCrontabMapper.selectOne(
                new QueryWrapper<SystemDevCrontab>()
                    .eq("id", id)
                    .last("limit 1"));
        Assert.notNull(model, "数据不存在");
        SystemDevCrontabDetailVo vo = new SystemDevCrontabDetailVo();
        BeanUtils.copyProperties(model, vo);
        vo.setLastTime(TimeUtil.timestampToDate(model.getLastTime()));
        return vo;
    }

    /**
     * 定时任务新增
     *
     * @author panweiliang
     * @param systemDevCrontabParam 参数
     */
    @Override
    public void add(SystemDevCrontabParam systemDevCrontabParam) {
        SystemDevCrontab model = new SystemDevCrontab();
        model.setName(systemDevCrontabParam.getName());
        model.setType(systemDevCrontabParam.getType());
        model.setSystem(systemDevCrontabParam.getSystem());
        model.setRemark(systemDevCrontabParam.getRemark());
        model.setCommand(systemDevCrontabParam.getCommand());
        model.setParams(systemDevCrontabParam.getParams());
        model.setStatus(systemDevCrontabParam.getStatus());
        model.setExpression(systemDevCrontabParam.getExpression());
        model.setCreateTime(System.currentTimeMillis() / 1000);
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        systemDevCrontabMapper.insert(model);
        Integer status = model.getStatus();
        if (status != null && status.intValue() == 1) {
            if (SystemDevCrontabEnum.COMMAND_ORDER_CHECK.getCode().equals(model.getCommand())) {
                OrderCheckRunnable orderCheckTask = new OrderCheckRunnable(model.getId(), model.getCommand(), iOrderService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(orderCheckTask, model.getExpression());
            } else if (SystemDevCrontabEnum.COMMAND_COUPON_RECEIVE_CHECK.getCode().equals(model.getCommand())) {
                CouponReceiveCheckRunnable couponReceiveCheckRunnable = new CouponReceiveCheckRunnable(model.getId(), model.getCommand(), iCouponReceiveService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(couponReceiveCheckRunnable, model.getExpression());
            } else if (SystemDevCrontabEnum.COMMAND_COUPON_RECEIVE_TIME_CHECK.getCode().equals(model.getCommand())) {
                CouponReceiveTimeCheckRunnable couponReceiveTimeCheckRunnable = new CouponReceiveTimeCheckRunnable(model.getId(), model.getCommand(), couponService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(couponReceiveTimeCheckRunnable, model.getExpression());
            } else {
                RefundOrderCheckRunnable refundOrderCheckTask = new RefundOrderCheckRunnable(model.getId(), model.getCommand(), iOrderRefundService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(refundOrderCheckTask, model.getExpression());
            }
        } else {
            if (SystemDevCrontabEnum.COMMAND_ORDER_CHECK.getCode().equals(model.getCommand())) {
                OrderCheckRunnable orderCheckTask = new OrderCheckRunnable(model.getId(), model.getCommand(), iOrderService, systemDevCrontabMapper);
                cronTaskRegistrar.removeCronTask(orderCheckTask);
            } else if (SystemDevCrontabEnum.COMMAND_COUPON_RECEIVE_CHECK.getCode().equals(model.getCommand())) {
                CouponReceiveCheckRunnable couponReceiveCheckRunnable = new CouponReceiveCheckRunnable(model.getId(), model.getCommand(), iCouponReceiveService, systemDevCrontabMapper);
                cronTaskRegistrar.removeCronTask(couponReceiveCheckRunnable);
            } else if (SystemDevCrontabEnum.COMMAND_COUPON_RECEIVE_TIME_CHECK.getCode().equals(model.getCommand())) {
                CouponReceiveTimeCheckRunnable couponReceiveTimeCheckRunnable = new CouponReceiveTimeCheckRunnable(model.getId(), model.getCommand(), couponService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(couponReceiveTimeCheckRunnable, model.getExpression());
            } else {
                RefundOrderCheckRunnable refundOrderCheckTask = new RefundOrderCheckRunnable(model.getId(), model.getCommand(), iOrderRefundService, systemDevCrontabMapper);
                cronTaskRegistrar.removeCronTask(refundOrderCheckTask);
            }
        }



    }

    /**
     * 定时任务编辑
     *
     * @author panweiliang
     * @param systemDevCrontabParam 参数
     */
    @Override
    public void edit(SystemDevCrontabParam systemDevCrontabParam) {
        SystemDevCrontab model = systemDevCrontabMapper.selectOne(
                new QueryWrapper<SystemDevCrontab>()
                    .eq("id",  systemDevCrontabParam.getId())
                    .last("limit 1"));
        Assert.notNull(model, "数据不存在!");

        model.setId(systemDevCrontabParam.getId());
        model.setName(systemDevCrontabParam.getName());
        model.setType(systemDevCrontabParam.getType());
        model.setRemark(systemDevCrontabParam.getRemark());
        model.setCommand(systemDevCrontabParam.getCommand());
        model.setParams(systemDevCrontabParam.getParams());
        model.setStatus(systemDevCrontabParam.getStatus());
        model.setExpression(systemDevCrontabParam.getExpression());
        model.setUpdateTime(System.currentTimeMillis() / 1000);
        systemDevCrontabMapper.updateById(model);
        Integer status = model.getStatus();
        if (status != null && status.intValue() == 1) {
            if (SystemDevCrontabEnum.COMMAND_ORDER_CHECK.getCode().equals(model.getCommand())) {
                OrderCheckRunnable orderCheckTask = new OrderCheckRunnable(model.getId(), model.getCommand(), iOrderService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(orderCheckTask, model.getExpression());
            } else {
                RefundOrderCheckRunnable refundOrderCheckTask = new RefundOrderCheckRunnable(model.getId(), model.getCommand(), iOrderRefundService, systemDevCrontabMapper);
                cronTaskRegistrar.addCronTask(refundOrderCheckTask, model.getExpression());
            }
        } else {
            if (SystemDevCrontabEnum.COMMAND_ORDER_CHECK.getCode().equals(model.getCommand())) {
                OrderCheckRunnable orderCheckTask = new OrderCheckRunnable(model.getId(), model.getCommand(), iOrderService, systemDevCrontabMapper);
                cronTaskRegistrar.removeCronTask(orderCheckTask);
            } else {
                RefundOrderCheckRunnable refundOrderCheckTask = new RefundOrderCheckRunnable(model.getId(), model.getCommand(), iOrderRefundService, systemDevCrontabMapper);
                cronTaskRegistrar.removeCronTask(refundOrderCheckTask);
            }
        }
    }

    /**
     * 定时任务删除
     *
     * @author panweiliang
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        SystemDevCrontab model = systemDevCrontabMapper.selectOne(
                new QueryWrapper<SystemDevCrontab>()
                    .eq("id", id)
                    .last("limit 1"));
        Assert.notNull(model, "数据不存在!");
        if (SystemDevCrontabEnum.COMMAND_ORDER_CHECK.getCode().equals(model.getCommand())) {
            OrderCheckRunnable orderCheckTask = new OrderCheckRunnable(model.getId(), model.getCommand(), iOrderService, systemDevCrontabMapper);
            cronTaskRegistrar.removeCronTask(orderCheckTask);
        } else {
            RefundOrderCheckRunnable refundOrderCheckTask = new RefundOrderCheckRunnable(model.getId(), model.getCommand(), iOrderRefundService, systemDevCrontabMapper);
            cronTaskRegistrar.removeCronTask(refundOrderCheckTask);
        }
        systemDevCrontabMapper.delete(new QueryWrapper<SystemDevCrontab>().eq("id", id));
    }

}
